package com.example.tao_city.mymusicplay;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private ViewPager mpager;
    private List<View> mlist = new ArrayList<View>();
    private View view1, view2;
    private PagerAdapter madapter;
    private ListView listView;
    private ArrayList<Music> musiclist;
    private ImageView view;
    private TextView timenow, time, songname, artname;
    private SeekBar Seekbar,shengyin;
    private boolean star = false;
    private LinearLayout laytop;
    private AudioManager am;

    private int duration, seekbartime;
    private int number = 0;
    private int status = 2;

    private Handler handler = new Handler();
    private ImageView previous, play, stop, next;
    private StatusChangedReceiver receiver;
    private static final int PROGRESS_INCREASE = 0;
    private static final int PROGRESS_PAUSE = 1;
    private static final int PROGRESS_RESET = 2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initlistdemoView();
        listview();
        bindStaatusChingedRecevier();
        initSeekBarHandler();
        setsound(shengyin);
        startService(new Intent(this, MusicService.class));
        status = MusicService.COMMAND_STOP;
    }

    @Override
    protected void onPause() {
        super.onPause();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);//注销广播
    }

    //注册广播接收器
    private void bindStaatusChingedRecevier() {
        receiver = new StatusChangedReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(MusicService.BROADCAST_MUSICSERVICE_UPDATE_STATUS);
        filter.addAction("android.media.VOLUME_CHANGED_ACTION");//添加对物理键控制声音的广播接收
        registerReceiver(receiver, filter);
    }

    private void initView() {
        mpager = findViewById(R.id.viewPager);
        laytop=findViewById(R.id.linearlayouttop);
        shengyin=findViewById(R.id.shengyin);
        //把页面转化为视图，等着加载到主页面中
        LayoutInflater mlayout = LayoutInflater.from(this);
        view1 = mlayout.inflate(R.layout.listview_main, null);
        view2 = mlayout.inflate(R.layout.songitem, null);
        //歌曲时间
        timenow = findViewById(R.id.timenow);
        time = findViewById(R.id.time);
        //进度条
        Seekbar = findViewById(R.id.seekbar);
        //4个播放状态控制按钮
        play = findViewById(R.id.play);
        previous = findViewById(R.id.previous);
        stop = findViewById(R.id.stop);
        next = findViewById(R.id.next);
        //歌曲信息
        songname = findViewById(R.id.songname);
        artname = findViewById(R.id.artname);

        previous.setOnClickListener(this);
        play.setOnClickListener(this);
        stop.setOnClickListener(this);
        next.setOnClickListener(this);


        //进度条监听控制
        Seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (status == MusicService.STATUS_PLAYING) {
                    Seekbar.setProgress(seekBar.getProgress());
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                    seekbartime = seekBar.getProgress();
                }
            }
        });
        //转动页面添加视图
        mlist.add(view1);
        mlist.add(view2);
        madapter = new PagerAdapter() {

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                View view = mlist.get(position);
                container.addView(view);
                return view;
            }

            @Override
            public int getCount() {
                return mlist.size();
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }
        };
        mpager.setAdapter(madapter);
        //视图滑动监听
        mpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                int item=position;
                switch (item){
                    case 0:
                        laytop.setVisibility(View.VISIBLE);
                        break;
                    case 1:
                        listView.setSelection(number);
                        laytop.setVisibility(View.GONE);
                        break;
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        //两个视图页面中的控件注册
        listView = view2.findViewById(R.id.songitem_listview);
        view = view1.findViewById(R.id.list_main_img);
    }

    //将音乐添加到数组中的函数
    private void initlistdemoView() {
        musiclist = Musiclist.getMusiclist();
        //避免重复添加音乐
        if (musiclist.isEmpty()) {
            Cursor mMusicCursor = this.getContentResolver().query(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
                    MediaStore.Audio.AudioColumns.TITLE);
            //标题
            int indexTitle = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE);
            //艺术家
            int indexArtist = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST);
            //总时长
            int indexTotalTime = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION);
            //路径
            int indexPath = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);

            /**通过mMusicCursor游标遍历数据库，并将Music类对象加载到ArrayList中*/
            for (mMusicCursor.moveToFirst(); !mMusicCursor.isAfterLast(); mMusicCursor
                    .moveToNext()) {
                String strTitle = mMusicCursor.getString(indexTitle);
                String strArtist = mMusicCursor.getString(indexArtist);
                String strTotoalTime = mMusicCursor.getString(indexTotalTime);
                String strPath = mMusicCursor.getString(indexPath);

                if (strArtist.equals("<unknown>"))
                    strArtist = "无艺术家";
                Music music = new Music(strTitle, strArtist, strPath, strTotoalTime);
                musiclist.add(music);
            }
        }
    }

    //将数组中的音乐通过简单适配器加载到list view中
    private void listview() {
        List<Map<String, String>> listmap = new ArrayList<Map<String, String>>();
        HashMap<String, String> map;
        SimpleAdapter simpleAdapter;
        for (Music music : musiclist) {
            map = new HashMap<String, String>();
            map.put("musicName", music.getMusicName());
            map.put("musicArtist", music.getMusicArtist());
            listmap.add(map);
        }
        String[] from = new String[]{"musicName", "musicArtist"};
        int[] to = {R.id.listview_songname, R.id.listview_artname};
        simpleAdapter = new SimpleAdapter(this, listmap, R.layout.listviewdemo, from, to);
        listView.setAdapter(simpleAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                number = position;
                sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
            }
        });
    }

    //可被调用的发送广播的函数
    private void sendBroadcastOnCommand(int command) {
        Intent intent = new Intent(MusicService.BROADCAST_MUSICSERVICE_CONTROL);
        intent.putExtra("command", command);
        switch (command) {
            case MusicService.COMMAND_PLAY:
                intent.putExtra("number", number);
                break;
            case MusicService.COMMAND_SEEK_TO:
                intent.putExtra("time", Seekbar.getProgress());
                break;
            case MusicService.COMMAND_PREVIOUS:
            case MusicService.COMMAND_NEXT:
            case MusicService.COMMAND_PAUSE:
            case MusicService.COMMAND_STOP:
            case MusicService.COMMAND_RESUME:
            default:
                break;
        }
        sendBroadcast(intent);
    }

    //接收广播的类
    class StatusChangedReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            //对物理键控制音量的监听事件反应
            if(intent.getAction().equals("android.media.VOLUME_CHANGED_ACTION")){
                int sound=am.getStreamVolume(AudioManager.STREAM_MUSIC);
                shengyin.setProgress(sound);
            }
            status = intent.getIntExtra("status", -1);
            switch (status) {
                case MusicService.STATUS_PLAYING:
                    handler.removeMessages(PROGRESS_INCREASE);
                    seekbartime = intent.getIntExtra("time", 0);
                    duration = intent.getIntExtra("duration", 0);
                    timenow.setText(formatTime(seekbartime));
                    time.setText(formatTime(duration));
                    songname.setText(intent.getStringExtra("musicnName"));
                    artname.setText(intent.getStringExtra("musicArtist"));
                    number = intent.getIntExtra("number", number);
                    listView.setSelection(number);
                    Seekbar.setMax(intent.getIntExtra("duration", 0));
                    handler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 0);
                    play.setImageResource(R.drawable.pause);
                    break;
                case MusicService.STATUS_PAUSED:
                    number = intent.getIntExtra("number", number);
                    listView.setSelection(number);
                    handler.sendEmptyMessage(PROGRESS_PAUSE);
                    play.setImageResource(R.drawable.play);
                    break;

                case MusicService.STATUS_STOPPED:
                    seekbartime = 0;
                    duration = 0;
                    timenow.setText(formatTime(seekbartime));
                    time.setText(formatTime(duration));
                    handler.sendEmptyMessage(PROGRESS_RESET);
                    play.setImageResource(R.drawable.play);
                    break;
                case MusicService.STATUS_COMPLETED:
                    number = intent.getIntExtra("number", 0);
                    if (number == Musiclist.getMusiclist().size() - 1) {
                        sendBroadcastOnCommand(MusicService.COMMAND_STOP);
                    } else {
                        sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                    }
                    listView.setSelection(number);
                    handler.sendEmptyMessage(PROGRESS_RESET);
                    play.setImageResource(R.drawable.play);
                    break;
                default:
                    break;
            }
        }
    }

    //屏蔽物理键调节音量是系统弹出来的Toast
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) {
            am.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, 0);
        }else if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP) {
            am.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, 0);
        }
        return true;
    }

    //格式化音乐时间
    private String formatTime(int mesc) {
        int minute = mesc / 1000 / 60;
        int second = mesc / 1000 % 60;
        String minutestring;
        String secondstring;
        if (minute < 10) {
            minutestring = "0" + minute;
        } else {
            minutestring = "" + minute;
        }
        if (second < 10) {
            secondstring = "0" + second;
        } else {
            secondstring = "" + second;
        }
        return minutestring + ":" + secondstring;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.play:
                switch (status) {
                    case MusicService.STATUS_PLAYING:
                        sendBroadcastOnCommand(MusicService.COMMAND_PAUSE);
                        break;
                    case MusicService.STATUS_PAUSED:
                        sendBroadcastOnCommand(MusicService.COMMAND_RESUME);
                        break;
                    case MusicService.COMMAND_STOP:
                        sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                }
                break;
            case R.id.previous:
                sendBroadcastOnCommand(MusicService.COMMAND_PREVIOUS);
                break;
            case R.id.stop:
                sendBroadcastOnCommand(MusicService.COMMAND_STOP);
                break;
            case R.id.next:
                sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                break;
        }
    }

    private void initSeekBarHandler() {
        handler = new Handler() {
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case PROGRESS_INCREASE:
                        if (Seekbar.getProgress() < duration) {
                            //进度条前进一秒
                            Seekbar.setProgress(seekbartime);
                            //seekBar.incrementProgressBy(1000);
                            handler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                            //修改显示当前进度的文本
                            timenow.setText(formatTime(seekbartime));
                            seekbartime += 1000;
                        }
                        break;
                    case PROGRESS_PAUSE:
                        handler.removeMessages(PROGRESS_INCREASE);
                        break;
                    case PROGRESS_RESET:
                        //重置进度条画面
                        handler.removeMessages(PROGRESS_INCREASE);
                        Seekbar.setProgress(0);
                        time.setText("00:00");
                        break;
                }
            }
        };
    }
    //Seekbar显示和控制音量
    private void setsound(SeekBar shengyin){
        am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        //获取最大声音和设置
        int maxsound=am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        shengyin.setMax(maxsound);
        //获取当前声音和设置
        int soundnow=am.getStreamVolume(AudioManager.STREAM_MUSIC);
        shengyin.setProgress(soundnow);
        shengyin.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                am.setStreamVolume(AudioManager.STREAM_MUSIC,seekBar.getProgress(),0);
                int sound=am.getStreamVolume(AudioManager.STREAM_MUSIC);
                seekBar.setProgress(sound);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });



    }
    private void setPinpu(){

    }
    private void loadingCover(String mediaUri) {
        MediaMetadataRetriever mediaMetadataRetriever=new MediaMetadataRetriever();
        mediaMetadataRetriever.setDataSource(mediaUri);
        byte[] picture = mediaMetadataRetriever.getEmbeddedPicture();
        Bitmap bitmap= BitmapFactory.decodeByteArray(picture,0,picture.length);
        view.setImageBitmap(bitmap);
    }
}
